package com.mobeedom.android.justinstalled;

import static com.mobeedom.android.justinstalled.AppSingleton.LOG_TAG;

import java.sql.SQLException;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.Where;
import com.mobeedom.android.justinstalled.db.DatabaseHelper;
import com.mobeedom.android.justinstalled.db.InstalledAppInfo;

public class IntentReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		String data = intent.getData().toString().replace("package:", "");
		boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);

		Log.d(LOG_TAG, "Action: " + intent.getAction());
		Log.d(LOG_TAG, "The DATA: " + data);
		Log.d(LOG_TAG, "Replacing: " + replacing);

		if (!replacing) {
			if ("android.intent.action.PACKAGE_ADDED".compareTo(intent.getAction()) == 0) {
				ApplicationInfo ai;
				try {
					ai = context.getPackageManager().getApplicationInfo(data.toString(), PackageManager.GET_META_DATA);
					InstalledAppInfo iai = new InstalledAppInfo(ai.loadLabel(context.getPackageManager()).toString(), ai.packageName, new Date().getTime());
					DatabaseHelper.getHelper(context)
							.getDaoInstalledAppInfoRuntime().create(iai);
				} catch (NameNotFoundException e) {
					Log.e(LOG_TAG, "Name not found : " + e.getMessage());
					e.printStackTrace();
				}
			}

			if ("android.intent.action.PACKAGE_REMOVED".compareTo(intent.getAction()) == 0) {
				DeleteBuilder<InstalledAppInfo, Integer> delB = DatabaseHelper.getHelper(context)
						.getDaoInstalledAppInfoRuntime().deleteBuilder();
				Where<InstalledAppInfo, Integer> where = delB.where();
				try {
					where.eq("packageName", data.toString());
					delB.setWhere(where);
					int ret = delB.delete();
					Log.d(LOG_TAG, "Removed " + ret + " rows pname = " + data.toString());
				} catch (SQLException e) {
					Log.e(LOG_TAG, e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
}